<template>
  <div class="input-upload">
    <a href="javascript:;" class="select-image" @click="onSelectImage">选择图片</a>

    <span v-show="previewImage !== ''"> | </span>

    <a href="javascript:;" class="clear-image" v-show="previewImage !== ''" @click="onClearImage">清空</a>

    <div class="preview">
      <img :src="previewImage" v-if="previewImage !== ''" />

      <span v-else class="preview-null" @click="onSelectImage">
        <i class="el-icon-picture icon"></i>
      </span>
    </div>

    <el-dialog v-model="visible" width="500px" title="上传图片" destroy-on-close>
      <el-upload
        class="upload"
        drag
        action="/api/upload"
        accept="image/*"
        :http-request="onUploadImage"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          拖拽图片到此处或 <em>点击上传</em>
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { uploadImage } from '@/services/upload.service'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'KInputUpload',
  props: {
    modelValue: String
  },
  setup (props, { emit }) {
    const visible = ref(false)
    const previewImage = ref(props.modelValue)

    // 选择图片
    const onSelectImage = () => {
      visible.value = true
    }

    // 上传图片
    const onUploadImage = async (f: any) => {
      try {
        const res = await uploadImage(f.file)
        previewImage.value = window.URL.createObjectURL(f.file)
        visible.value = false
        f.onSuccess(res)
        emit('update:modelValue', res)
      } catch (e) {
        ElMessage.error(e.message)
        f.onError(e.message)
      }
    }

    // 清空图片
    const onClearImage = () => {
      previewImage.value = ''
      emit('update:modelValue', '')
    }

    return {
      visible,
      previewImage,
      onSelectImage,
      onUploadImage,
      onClearImage
    }
  }
})
</script>

<style scoped lang="scss">
.input-upload {
  .select-image, .clear-image {
    color: #d556ff;
    text-decoration: none;
    &:hover {
      text-decoration: underline;
    }
  }
  .preview {
    $width: 300px;
    $height: 180px;
    img {
      display: block;
      width: $width;
      height: $height;
      border: solid 1px #dcdfe6;
      border-radius: 6px;
    }
    &-null {
      display: block;
      text-align: center;
      width: $width;
      height: $height;
      line-height: $height;
      border: solid 1px #dcdfe6;
      border-radius: 6px;
      cursor: pointer;
      .icon {
        color: #999;
        font-size: 26px;
      }
    }
  }
}
.upload ::v-deep {
  .el-upload-dragger, .el-upload {
    width: 100%;
    height: 200px;
  }
  .el-upload-list--text {
    position: absolute;
    bottom: 10px;
    left: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
  }
}
</style>
